package com.smyh.UIM.device;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.NotificationCompat;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.smyh.UIM.HostFragment;
import com.smyh.UIM.R;
import com.smyh.cache.UIM.device.DeviceUpdateFm_Cache;
import com.smyh.util.TxtUtil;

/**
 * Created by Administrator on 2016/7/27.
 */
public class DeviceUpdateFm extends Fragment {

    /**
     * 指示器相别单选钮
     */
    RadioButton aRadio,bRadio,cRadio;
    /**
     * 字节进度显示标签
     */
    public static TextView progressBytes,fileNameText;

    /**
     *文件选择按钮，升级指令按钮
     */
    Button selectFileBtn,updateBtn;

    static Handler handler;
    /**
     * 文件资源地址
     */
    Uri uri;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.activity_device_update,container,false);

        initView(view);
        initEvent();

        handler = new Handler(){

            @Override
            public void handleMessage(Message msg) {
                switch (msg.what){
                    case 1:{
                        String progressStr = (String) msg.getData().get("1");
                        progressBytes.setText(progressStr);

                        break;
                    }
                    case 2:{

                        break;
                    }
                }
//                super.handleMessage(msg);
            }
        };
        return view;
    }

    public static void freshProgress(Message msg){
        handler.sendMessage(msg);
    }
    private void initEvent() {
        aRadio.setOnCheckedChangeListener(radioCheckList);
        bRadio.setOnCheckedChangeListener(radioCheckList);
        cRadio.setOnCheckedChangeListener(radioCheckList);

        selectFileBtn.setOnClickListener(updateClickListen);
        updateBtn.setOnClickListener(updateClickListen);
    }
    private void initView(View view){
        DeviceUpdateFm_Cache.updateType = 1;
        aRadio = (RadioButton) view.findViewById(R.id.aRadio);
        bRadio = (RadioButton) view.findViewById(R.id.bRadio);
        cRadio = (RadioButton) view.findViewById(R.id.cRadio);

        progressBytes = (TextView) view.findViewById(R.id.progressByts);
        fileNameText = (TextView) view.findViewById(R.id.fileName);

        selectFileBtn = (Button) view.findViewById(R.id.selectFile);
        updateBtn = (Button) view.findViewById(R.id.updateButton);

    }
    CompoundButton.OnCheckedChangeListener radioCheckList = new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

            if(isChecked){
                String str = buttonView.getText().toString();
                if("A".equalsIgnoreCase(str)){
                    DeviceUpdateFm_Cache.phaseNum = 1;
                }
                if("B".equalsIgnoreCase(str)){
                    DeviceUpdateFm_Cache.phaseNum = 2;
                }
                if("C".equalsIgnoreCase(str)){
                    DeviceUpdateFm_Cache.phaseNum = 3;
                }
            }
        }
    };

    View.OnClickListener updateClickListen = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            int idV = v.getId();
            switch (idV){
                case R.id.selectFile:{
                    Intent it2 = new Intent(Intent.ACTION_GET_CONTENT);
                    it2.setType("*/*");
                    it2.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
                    startActivityForResult(Intent.createChooser(it2, "选个文件"),1);
                    break;
                }
                case R.id.updateButton:{
                    //设备透传：//或者处于串口数据运行模式：
                    if (HostFragment.connection_btn.isChecked() ) {
//                        updateBtn.setEnabled(true);
                        if (uri == null || "".equals(uri.toString())) {
                            Toast.makeText(getContext(),"没有选择bin文件！",Toast.LENGTH_SHORT).show();
                        }else {
                            String realPath = getRealFilePath(getContext(),uri);
                            TxtUtil.updateProgramPackForDevice(realPath);
                        }
                    } else {
//                        updateBtn.setEnabled(false);
                        Toast.makeText(getContext(),"请连接设备，使数据透传！",Toast.LENGTH_SHORT).show();
                    }

                    break;
                }
            }

        }
    };

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == 1 && resultCode == Activity.RESULT_OK) {

            uri = data.getData();
            String realPath = getRealFilePath(getContext(), uri);
            fileNameText.setText(realPath);

        }
    }
    /**
     * Try to return the absolute file path from the given Uri
     *
     * @param context
     * @param uri
     * @return the file path or null
     */
    public static String getRealFilePath(final Context context, final Uri uri ) {
        if ( null == uri ) return null;
        final String scheme = uri.getScheme();
        String data = null;
        if ( scheme == null )
            data = uri.getPath();
        else if ( ContentResolver.SCHEME_FILE.equals( scheme ) ) {
            data = uri.getPath();
        } else if ( ContentResolver.SCHEME_CONTENT.equals( scheme ) ) {
            Cursor cursor = context.getContentResolver().query( uri, new String[] { MediaStore.Images.ImageColumns.DATA }, null, null, null );
            if ( null != cursor ) {
                if ( cursor.moveToFirst() ) {
                    int index = cursor.getColumnIndex( MediaStore.Images.ImageColumns.DATA );
                    if ( index > -1 ) {
                        data = cursor.getString( index );
                    }
                }
                cursor.close();
            }
        }
        return data;
    }
}
